package com.zenithmind.mall.service.impl;

import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.mall.mapper.ProductStatisticsMapper;
import com.zenithmind.mall.pojo.entity.ProductStatistics;
import com.zenithmind.mall.service.ProductStatisticsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品统计服务实现类 - 遵循单一职责原则，专门负责商品统计相关操作
 * 
 * @author ZenithMind Team
 * @since 2025-07-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductStatisticsServiceImpl implements ProductStatisticsService {

    private final ProductStatisticsMapper productStatisticsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increaseViewCount(String id) {
        ProductStatistics statistics = getOrCreateStatistics(id);
        statistics.increaseViewCount();
        
        int result = productStatisticsMapper.updateById(statistics);
        if (result <= 0) {
            log.warn("增加浏览量失败: productId={}", id);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean increaseSalesCount(String id, Integer quantity) {
        if (quantity == null || quantity <= 0) {
            throw new BusinessException("销售数量必须大于0");
        }
        
        ProductStatistics statistics = getOrCreateStatistics(id);
        statistics.increaseSalesCount(quantity);
        
        int result = productStatisticsMapper.updateById(statistics);
        if (result <= 0) {
            throw new BusinessException("增加销量失败");
        }
        
        log.info("增加销量成功: productId={}, quantity={}, totalSales={}", 
                id, quantity, statistics.getSalesCount());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean increaseFavoriteCount(String id) {
        ProductStatistics statistics = getOrCreateStatistics(id);
        statistics.increaseFavoriteCount();
        
        int result = productStatisticsMapper.updateById(statistics);
        if (result <= 0) {
            throw new BusinessException("增加收藏量失败");
        }
        
        log.info("增加收藏量成功: productId={}, favoriteCount={}", 
                id, statistics.getFavoriteCount());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean decreaseFavoriteCount(String id) {
        ProductStatistics statistics = getOrCreateStatistics(id);
        statistics.decreaseFavoriteCount();
        
        int result = productStatisticsMapper.updateById(statistics);
        if (result <= 0) {
            throw new BusinessException("减少收藏量失败");
        }
        
        log.info("减少收藏量成功: productId={}, favoriteCount={}", 
                id, statistics.getFavoriteCount());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateProductRating(String id, Double rating) {
        if (rating == null || rating < 0 || rating > 5) {
            throw new BusinessException("评分必须在0-5之间");
        }
        
        ProductStatistics statistics = getOrCreateStatistics(id);
        
        // 这里简化处理，实际应该重新计算平均评分
        statistics.setAverageRating(rating);
        
        int result = productStatisticsMapper.updateById(statistics);
        if (result <= 0) {
            throw new BusinessException("更新商品评分失败");
        }
        
        log.info("更新商品评分成功: productId={}, rating={}", id, rating);
        return true;
    }

    @Override
    public Integer getViewCount(String id) {
        ProductStatistics statistics = productStatisticsMapper.selectById(id);
        return statistics != null ? statistics.getViewCount() : 0;
    }

    @Override
    public Integer getSalesCount(String id) {
        ProductStatistics statistics = productStatisticsMapper.selectById(id);
        return statistics != null ? statistics.getSalesCount() : 0;
    }

    @Override
    public Integer getFavoriteCount(String id) {
        ProductStatistics statistics = productStatisticsMapper.selectById(id);
        return statistics != null ? statistics.getFavoriteCount() : 0;
    }

    @Override
    public Double getAverageRating(String id) {
        ProductStatistics statistics = productStatisticsMapper.selectById(id);
        return statistics != null ? statistics.getAverageRating() : 0.0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUpdateStatistics() {
        // 这里可以实现批量更新统计数据的逻辑
        // 例如：从订单表重新计算销量，从评价表重新计算评分等
        
        log.info("批量更新商品统计数据完成");
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean recalculateStatistics(String id) {
        ProductStatistics statistics = getOrCreateStatistics(id);
        
        // 这里可以实现重新计算单个商品统计数据的逻辑
        // 例如：从订单表重新计算销量，从评价表重新计算评分等
        
        int result = productStatisticsMapper.updateById(statistics);
        if (result <= 0) {
            throw new BusinessException("重新计算统计数据失败");
        }
        
        log.info("重新计算商品统计数据成功: productId={}", id);
        return true;
    }

    @Override
    public Object getStatisticsReport(String id) {
        ProductStatistics statistics = productStatisticsMapper.selectById(id);
        if (statistics == null) {
            return null;
        }
        
        // 构建统计报告
        return new Object() {
            public String getProductId() { return statistics.getProductId(); }
            public Integer getSalesCount() { return statistics.getSalesCount(); }
            public Integer getViewCount() { return statistics.getViewCount(); }
            public Integer getFavoriteCount() { return statistics.getFavoriteCount(); }
            public Integer getReviewCount() { return statistics.getReviewCount(); }
            public Double getAverageRating() { return statistics.getAverageRating(); }
            public Double getPositiveReviewRate() { return statistics.getPositiveReviewRate(); }
            public Boolean isRecommend() { return statistics.isRecommendProduct(); }
            public Boolean isNew() { return statistics.isNewProduct(); }
            public Boolean isHot() { return statistics.isHotProduct(); }
        };
    }

    /**
     * 获取或创建商品统计信息
     */
    private ProductStatistics getOrCreateStatistics(String productId) {
        ProductStatistics statistics = productStatisticsMapper.selectById(productId);
        
        if (statistics == null) {
            // 创建新的统计记录
            statistics = new ProductStatistics();
            statistics.setProductId(productId);
            statistics.setSalesCount(0);
            statistics.setViewCount(0);
            statistics.setFavoriteCount(0);
            statistics.setReviewCount(0);
            statistics.setPositiveReviewCount(0);
            statistics.setAverageRating(0.0);
            statistics.setIsRecommend(0);
            statistics.setIsNew(1);
            statistics.setIsHot(0);
            
            productStatisticsMapper.insert(statistics);
            log.info("创建商品统计记录: productId={}", productId);
        }
        
        return statistics;
    }
}
